package com.rajeshDyadav.mean;

import org.apache.poi.ss.formula.functions.Irr;

public class IRR2 {

    private double[] prepareCf(double cf0, int tenure, double cf) {
	double[] cashFlows = new double[tenure + 1];
	cashFlows[0] = cf0;
	for (int i = 1; i <= tenure; i++) {
	    cashFlows[i] = cf;
	}
	return cashFlows;
    }

    private double irrDiff(double irrExp, double amt, int tenure, double cf) {
	double cashFlows[] = prepareCf(amt, tenure, cf);
	double irrRet, irrDiff;
	irrRet = Irr.irr(cashFlows);
	irrDiff = Double.valueOf(Double.valueOf(irrRet) - Double.valueOf(irrExp));
	// BigDecimal bigDecimal = new BigDecimal(irrDiff);
	// bigDecimal = bigDecimal.divide(new BigDecimal("1"), 3,
	// BigDecimal.ROUND_HALF_UP);
	// irrDiff = Double.parseDouble(bigDecimal.toPlainString());

	return irrDiff;
    }

    public static void main(String[] args) {
	double amt = -50000;
	int tenure = 5;	
	double irrExp = 0.064;

	IRR2 irr2 = new IRR2();
	irr2.guessCF(amt, tenure, irrExp);
    }

    public double guessCF(double amt, int tenure, double irrExp) {
	double cf = 50000;
	double irrDiff;
	double lowVal = 0.0, highVal = 0.0, meanVal = cf;
	double MIN = 1, MAX = 100000;

	irrDiff = irrDiff(irrExp, amt, tenure, cf);

	double loopingData[] = new double[3];
	int exitCount = 0;
	while (irrDiff != 0.0000) {

	    if (exitCount < 3) {
		loopingData[exitCount++] = meanVal;
	    } else {
		exitCount = 0;
		if ((loopingData[0] == loopingData[1]) && (loopingData[0] == loopingData[2])) {
		    System.out.println("force exit");
		    break;
		}
	    }

	    if (irrDiff <= 0.0001) {
		System.out.println("Lesser");
		lowVal = meanVal + 1;
		MIN = meanVal + 1;
		highVal = MAX;
	    } else if (irrDiff > 0.0001) {
		System.out.println("Greater");
		lowVal = MIN;
		highVal = meanVal - 1;
		MAX = meanVal - 1;
	    }

	    meanVal = Double.valueOf((Double.valueOf(lowVal) + Double.valueOf(highVal)) / 2);
	    System.out.println("meanVal ..> " + meanVal);
	    irrDiff = irrDiff(irrExp, amt, tenure, meanVal);
	}
	System.out.println("Required CF ..> " + meanVal);
	return meanVal;
    }
}
